<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="此为龙果学院课程笔记，记录以供以后翻看 缓存雪崩缓存雪崩这种场景，缓存架构中非常重要的一个环节，应对缓存雪崩的解决方案，避免缓存雪崩的时候，造成整个系统崩溃，带来巨大的经济损失">
<meta name="keywords" content="多级缓存架构">
<meta property="og:type" content="article">
<meta property="og:title" content="高可用缓存架构实战6-缓存雪崩及解决方案">
<meta property="og:url" content="http://www.saily.top/2018/06/12/cache06/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="此为龙果学院课程笔记，记录以供以后翻看 缓存雪崩缓存雪崩这种场景，缓存架构中非常重要的一个环节，应对缓存雪崩的解决方案，避免缓存雪崩的时候，造成整个系统崩溃，带来巨大的经济损失">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.saily.top/img/cache/缓存雪崩的过程和后果.png">
<meta property="og:image" content="http://www.saily.top/img/cache/缓存雪崩的事前事中事后的解决方案.png">
<meta property="og:image" content="http://www.saily.top/img/cache/缓存穿透的现象.png">
<meta property="og:updated_time" content="2018-08-25T07:18:44.512Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="高可用缓存架构实战6-缓存雪崩及解决方案">
<meta name="twitter:description" content="此为龙果学院课程笔记，记录以供以后翻看 缓存雪崩缓存雪崩这种场景，缓存架构中非常重要的一个环节，应对缓存雪崩的解决方案，避免缓存雪崩的时候，造成整个系统崩溃，带来巨大的经济损失">
<meta name="twitter:image" content="http://www.saily.top/img/cache/缓存雪崩的过程和后果.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/06/12/cache06/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>高可用缓存架构实战6-缓存雪崩及解决方案 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/06/12/cache06/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">高可用缓存架构实战6-缓存雪崩及解决方案
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-12T21:19:12+08:00">6月 12 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/高可用缓存架构实战/" itemprop="url" rel="index"><span itemprop="name">高可用缓存架构实战</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>此为龙果学院课程笔记，记录以供以后翻看</p>
<h1 id="缓存雪崩"><a href="#缓存雪崩" class="headerlink" title="缓存雪崩"></a>缓存雪崩</h1><p>缓存雪崩这种场景，缓存架构中非常重要的一个环节，应对缓存雪崩的解决方案，避免缓存雪崩的时候，造成整个系统崩溃，带来巨大的经济损失</p>
<a id="more"></a>
<h2 id="缓存雪崩的过程和后果"><a href="#缓存雪崩的过程和后果" class="headerlink" title="缓存雪崩的过程和后果"></a>缓存雪崩的过程和后果</h2><p>缓存雪崩，一般首先是redis集群彻底崩溃，它导致崩溃的流程如下：</p>
<ol>
<li>redis集群彻底崩溃</li>
<li>缓存服务大量对redis的请求hang住，占用资源</li>
<li>缓存服务大量的请求打到源头服务去查询mysql，直接打死mysql</li>
<li>源头服务因为mysql被打死也崩溃，对源服务的请求也hang住，占用资源</li>
<li>缓存服务大量的资源全部耗费在访问redis和源服务无果，最后自己被拖死，无法提供服务</li>
<li>nginx无法访问缓存服务，redis和源服务，只能基于本地缓存提供服务，但是缓存过期后，没有数据提供</li>
<li>网站崩溃</li>
</ol>
<p><img src="/img/cache/缓存雪崩的过程和后果.png" alt="缓存雪崩的过程和后果"></p>
<h1 id="缓存雪崩的解决方案"><a href="#缓存雪崩的解决方案" class="headerlink" title="缓存雪崩的解决方案"></a>缓存雪崩的解决方案</h1><p>相对来说，考虑的比较完善的一套方案，分为事前，事中，事后三个层次去思考怎么来应对缓存雪崩的场景</p>
<h2 id="事前解决方案"><a href="#事前解决方案" class="headerlink" title="事前解决方案"></a>事前解决方案</h2><p>所谓事前解决方案，就是发生缓存雪崩之前，事情之前，怎么去避免redis彻底挂掉。</p>
<p>那就是保证redis的高可用性，我们利用redis本身的高可用性，复制，主从架构等功能，操作主节点去读写，数据同步到从节点，一旦主节点挂掉，从节点就跟上。</p>
<p>一般是建议双机房部署，一套redis cluster，部分机器在一个机房，另一部分机器在另外一个机房。</p>
<p>还有一种部署方式，两套redis cluster，两套redis cluster之间做一个数据的同步，redis集群是可以搭建成树状的结构的。一旦单个机房出了故障，至少另外一个机房还能有些redis实例提供服务。</p>
<h2 id="事中解决方案"><a href="#事中解决方案" class="headerlink" title="事中解决方案"></a>事中解决方案</h2><p>如果redis cluster已经彻底崩溃了，已经开始大量的访问无法访问到redis了，那之前文章讲到过的多级缓存就起作用了。</p>
<p>ehcache缓存，第一应对零散的redis中数据被清除掉的现象，另外一个主要是预防redis彻底崩溃。这样多台机器上部署的缓存服务实例的内存中，还有一套ehcache的缓存，可以基于本地的ehcache的缓存提供一部分的数据。</p>
<p>一旦redis集群彻底崩溃了需要做以下几个步骤：</p>
<ol>
<li>对redis的访问做资源隔离，避免所有资源hang在访问redis上</li>
<li>对redis访问失败的情况做相应的熔断和降级策略</li>
<li>使用ehcache本地缓存</li>
<li>对源服务访问的限流以及资源隔离（mysql层）</li>
</ol>
<h2 id="事后解决方案"><a href="#事后解决方案" class="headerlink" title="事后解决方案"></a>事后解决方案</h2><p>如何恢复Redis Cluster，有两种情况</p>
<ol>
<li>redis数据可以恢复，做了备份，redis数据备份和恢复，redis重新启动起来</li>
<li>redis数据彻底丢失了，或者数据过旧，快速缓存预热，redis重新启动起来</li>
</ol>
<p>其实这套方案没什么东西，事前的Redis文章前面也说了，事中ehcache也做过了。但是，如何将缓存服务如何设计成高可用的架构，需要配合Hystrix来开发。我们的熔断，降级，限流等等操作都需要Hystrix的配合。</p>
<p><a href="http://www.saily.top/categories/hystrix/">Hystrix系列文章</a></p>
<p><img src="/img/cache/缓存雪崩的事前事中事后的解决方案.png" alt="缓存雪崩的事前事中事后的解决方案"></p>
<h1 id="使用Hystrix对Redis进行资源隔离"><a href="#使用Hystrix对Redis进行资源隔离" class="headerlink" title="使用Hystrix对Redis进行资源隔离"></a>使用Hystrix对Redis进行资源隔离</h1><p>接下来就要对redis的访问这一块加上保护措施，给商品服务的访问加上限流的保护措施。redis这一块，全都用hystrix的command进行封装，做资源隔离，确保redis的访问只能在固定的线程池内的资源来进行访问，哪怕是redis访问的很慢，有等待和超时，也不要紧，只有少量额线程资源用来访问，缓存服务不会被拖垮。</p>
<p>找到之前的缓存项目<a href="https://github.com/sail-y/eshop-cache，引入Hystrix的依赖" target="_blank" rel="noopener">https://github.com/sail-y/eshop-cache，引入Hystrix的依赖</a></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.netflix.hystrix<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hystrix-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.5.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.netflix.hystrix<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hystrix-metrics-event-stream<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.4.10<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>在CacheServiceImpl里有几处用到redis的地方，我们就需要开发几个相应的command。</p>
<h2 id="SaveProductInfo2RedisCacheCommand"><a href="#SaveProductInfo2RedisCacheCommand" class="headerlink" title="SaveProductInfo2RedisCacheCommand"></a>SaveProductInfo2RedisCacheCommand</h2><p><strong>SaveProductInfo2RedisCacheCommand.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yangfan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/06/12</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaveProductInfo2RedisCacheCommand</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">Boolean</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ProductInfo productInfo;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SaveProductInfo2RedisCacheCommand</span><span class="params">(ProductInfo productInfo)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">super</span>(HystrixCommandGroupKey.Factory.asKey(<span class="string">"RedisGroup"</span>));</span><br><span class="line">        <span class="keyword">this</span>.productInfo = productInfo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Boolean <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringRedisTemplate redisTemplate = SpringContext.getApplicationContext().getBean(StringRedisTemplate.class);</span><br><span class="line"></span><br><span class="line">        String key = <span class="string">"product_info_"</span> + productInfo.getId();</span><br><span class="line">        redisTemplate.opsForValue().set(key, JSON.toJSONString(productInfo));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后用command替换之前的实现</p>
<p><strong>CacheServiceImpl.saveProductInfo2RedisCache</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将商品信息保存到redis中</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> productInfo</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveProductInfo2RedisCache</span><span class="params">(ProductInfo productInfo)</span> </span>&#123;</span><br><span class="line">    SaveProductInfo2RedisCacheCommand command = <span class="keyword">new</span> SaveProductInfo2RedisCacheCommand(productInfo);</span><br><span class="line">    command.execute();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="SaveShopInfo2RedisCacheCommand"><a href="#SaveShopInfo2RedisCacheCommand" class="headerlink" title="SaveShopInfo2RedisCacheCommand"></a>SaveShopInfo2RedisCacheCommand</h2><p><strong>SaveShopInfo2RedisCacheCommand.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 保存商品信息到Redis</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yangfan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/06/12</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaveShopInfo2RedisCacheCommand</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">Boolean</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ShopInfo shopInfo;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SaveShopInfo2RedisCacheCommand</span><span class="params">(ShopInfo shopInfo)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">super</span>(HystrixCommandGroupKey.Factory.asKey(<span class="string">"RedisGroup"</span>));</span><br><span class="line">        <span class="keyword">this</span>.shopInfo = shopInfo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Boolean <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringRedisTemplate redisTemplate = SpringContext.getApplicationContext().getBean(StringRedisTemplate.class);</span><br><span class="line"></span><br><span class="line">        String key = <span class="string">"shop_info_"</span> + shopInfo.getId();</span><br><span class="line">        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(shopInfo));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后用command替换之前的实现</p>
<p><strong>CacheServiceImpl.saveShopInfo2RedisCache</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将店铺信息保存到redis中</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> shopInfo</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveShopInfo2RedisCache</span><span class="params">(ShopInfo shopInfo)</span> </span>&#123;</span><br><span class="line">    SaveShopInfo2RedisCacheCommand command = <span class="keyword">new</span> SaveShopInfo2RedisCacheCommand(shopInfo);</span><br><span class="line">    command.execute();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="GetProductInfoFromRedisCacheCommand"><a href="#GetProductInfoFromRedisCacheCommand" class="headerlink" title="GetProductInfoFromRedisCacheCommand"></a>GetProductInfoFromRedisCacheCommand</h2><p><strong>GetProductInfoFromRedisCacheCommand.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 从Redis获取商品Command</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yangfan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/06/12</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetProductInfoFromRedisCacheCommand</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">ProductInfo</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long productId;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GetProductInfoFromRedisCacheCommand</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">super</span>(HystrixCommandGroupKey.Factory.asKey(<span class="string">"RedisGroup"</span>));</span><br><span class="line">        <span class="keyword">this</span>.productId = productId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> ProductInfo <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringRedisTemplate redisTemplate = SpringContext.getApplicationContext().getBean(StringRedisTemplate.class);</span><br><span class="line"></span><br><span class="line">        String key = <span class="string">"product_info_"</span> + productId;</span><br><span class="line">        String json = redisTemplate.opsForValue().get(key);</span><br><span class="line">        <span class="keyword">if</span> (json != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> JSONObject.parseObject(json, ProductInfo.class);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后用command替换之前的实现</p>
<p><strong>CacheServiceImpl.getProductInfoFromRedisCache</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 从Redis从获取商品信息</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ProductInfo <span class="title">getProductInfoFromRedisCache</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    GetProductInfoFromRedisCacheCommand command = <span class="keyword">new</span> GetProductInfoFromRedisCacheCommand(id);</span><br><span class="line">    <span class="keyword">return</span> command.execute();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="GetShopInfoFromRedisCacheCommand"><a href="#GetShopInfoFromRedisCacheCommand" class="headerlink" title="GetShopInfoFromRedisCacheCommand"></a>GetShopInfoFromRedisCacheCommand</h2><p><strong>GetShopInfoFromRedisCacheCommand.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 从Redis获取店铺信息Command</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yangfan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/06/12</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetShopInfoFromRedisCacheCommand</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">ShopInfo</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long shopId;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GetShopInfoFromRedisCacheCommand</span><span class="params">(Long shopId)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">super</span>(HystrixCommandGroupKey.Factory.asKey(<span class="string">"RedisGroup"</span>));</span><br><span class="line">        <span class="keyword">this</span>.shopId = shopId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> ShopInfo <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringRedisTemplate redisTemplate = SpringContext.getApplicationContext().getBean(StringRedisTemplate.class);</span><br><span class="line"></span><br><span class="line">        String key = <span class="string">"shop_info_"</span> + shopId;</span><br><span class="line">        String json = redisTemplate.opsForValue().get(key);</span><br><span class="line">        <span class="keyword">if</span> (json != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> JSONObject.parseObject(json, ShopInfo.class);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后用command替换之前的实现</p>
<p><strong>CacheServiceImpl.getShopInfoFromRedisCache</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 从Redis中获取商品店铺信息</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ShopInfo <span class="title">getShopInfoFromRedisCache</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    GetShopInfoFromRedisCacheCommand command = <span class="keyword">new</span> GetShopInfoFromRedisCacheCommand(id);</span><br><span class="line">    <span class="keyword">return</span> command.execute();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="使用Hystrix对Redis访问进行降级"><a href="#使用Hystrix对Redis访问进行降级" class="headerlink" title="使用Hystrix对Redis访问进行降级"></a>使用Hystrix对Redis访问进行降级</h1><p>上面已经通过hystrix command对redis的访问进行了资源隔离，避免redis访问频繁失败，或者频繁超时的时候，耗尽大量的tomcat容器的资源去hang在redis的访问上。</p>
<p>这样就限定只有一部分线程资源可以用来访问redis，如果redis集群彻底崩溃了，这个时候，可能command对redis的访问大量的报错和timeout超时，熔断（短路），我们就需要对redis进行降级，用Hystrix的fallback机制。建议是使用fail silent模式，fallback里面直接返回一个空值，比如一个null，最简单。</p>
<p>在外面调用redis的代码（CacheService类），只要你把timeout、熔断、熔断恢复、降级，都做好了，是感知不到redis的访问异常的。可能会出现的情况是，当redis集群崩溃的时候，CacheService会获取到的是大量的null空值。</p>
<p>根据这个null空值，我们还可以去做多级缓存的降级访问，nginx本地缓存，redis分布式集群缓存，ehcache本地缓存等等。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> ProductInfo <span class="title">getFallback</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>顺便回顾一下之前CacheController的代码，在从redis里获取null值以后，会自动去别的地方一步步获取。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping</span>(<span class="string">"/getProductInfo"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> ProductInfo <span class="title">getProductInfo</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 先从Redis从获取数据</span></span><br><span class="line">    ProductInfo productInfo = cacheService.getProductInfoFromRedisCache(productId);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (productInfo != <span class="keyword">null</span>) &#123;</span><br><span class="line">        System.out.println(<span class="string">"=================从redis中获取缓存，商品信息="</span> + productInfo);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (productInfo == <span class="keyword">null</span>) &#123;</span><br><span class="line">        productInfo = cacheService.getProductInfoFromLocalCache(productId);</span><br><span class="line">        System.out.println(<span class="string">"================从ehcache从获取缓存，商品信息="</span> + productInfo);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (productInfo == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 就需要从数据源重新拉取数据，重建缓存，模拟获取</span></span><br><span class="line">        String productInfoJSON = <span class="string">"&#123;\"id\": "</span> + productId + <span class="string">", \"name\": \"iphone7手机\", \"price\": 5599, \"pictureList\":\"a.jpg,b.jpg\", \"specification\": \"iphone7的规格\", \"service\": \"iphone7的售后服务\", \"color\": \"红色,白色,黑色\", \"size\": \"5.5\", \"shopId\": 2, \"modifiedTime\": \"2018-02-21 22:11:34\"&#125;"</span>;</span><br><span class="line">        productInfo = JSONObject.parseObject(productInfoJSON, ProductInfo.class);</span><br><span class="line">        <span class="comment">// 将数据推送到一个内存队列中</span></span><br><span class="line">        RebuildCacheQueue rebuildCacheQueue = RebuildCacheQueue.getInstance();</span><br><span class="line">        rebuildCacheQueue.putProductInfo(productInfo);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> productInfo;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>经过这样一个简单的改造，我们使用Hystrix对redis的线程资源隔离和降级都很容易的完成了。</p>
<h1 id="Redis集群崩溃定制化熔断策略"><a href="#Redis集群崩溃定制化熔断策略" class="headerlink" title="Redis集群崩溃定制化熔断策略"></a>Redis集群崩溃定制化熔断策略</h1><p>缓存雪崩的事中解决方案</p>
<p>redis集群崩溃的时候，Hystrix会怎么样？</p>
<ol>
<li>大量的等待，超时，报错</li>
<li>如果是短时间内报错，会直接走fallback降级，直接返回null</li>
<li>超时控制，应该是判断redis访问超过了多长时间，就直接给报错timeout了</li>
</ol>
<p>不推荐用默认的值，一般不太精准，redis的访问先统计一下访问时长的百分比，hystrix dashboard里可以看到TP90，TP95，TP99的时间分别是多少。一般redis访问TP99在100ms以内，那么此时timeout时长稍微设置多一些，比如100ms。</p>
<h2 id="timeout设置"><a href="#timeout设置" class="headerlink" title="timeout设置"></a>timeout设置</h2><p>HystrixCommandProperties.Setter()<br>   .withExecutionTimeoutInMilliseconds(int value)</p>
<p>意义在于哪里？一旦redis出现了大面积的故障，此时肯定是访问的时候大量的超过100ms，大量的在等待和超时，这样就可以确保大量的请求不会hang住过长的时间，比如hang住个1s，500ms。如果100ms直接就报timeout，就会走fallback降级了。</p>
<h2 id="熔断策略"><a href="#熔断策略" class="headerlink" title="熔断策略"></a>熔断策略</h2><p>开启熔断有2个参数</p>
<h3 id="circuitBreaker-requestVolumeThreshold"><a href="#circuitBreaker-requestVolumeThreshold" class="headerlink" title="circuitBreaker.requestVolumeThreshold"></a>circuitBreaker.requestVolumeThreshold</h3><p>设置一个rolling window，滑动窗口中，最少要有多少个请求时，才触发开启短路。举例，如果设置为20（默认值），那么在一个10秒的滑动窗口内，如果只有19个请求，即使这19个请求都是异常的，也是不会触发开启短路器的。</p>
<p>HystrixCommandProperties.Setter()<br>   .withCircuitBreakerRequestVolumeThreshold(int value)</p>
<p>我们应该根据我们自己的平时的访问流量去设置，而不是用默认值，比如，我们认为平时一般的时候，流量也可以在每秒在QPS 100，10秒的滑动窗口就是1000，一般可以设置600或者800一个值，需要根据自己的系统的流量去设置。假如你设置的太少了，或者太多了，都不太合适。举个例子，你设置一个20，结果在晚上最低峰的时候，刚好是30，可能晚上的时候因为访问不频繁，大量的找不到缓存，可能超时频繁了一些，结果直接就给短路了。</p>
<h3 id="circuitBreaker-errorThresholdPercentage"><a href="#circuitBreaker-errorThresholdPercentage" class="headerlink" title="circuitBreaker.errorThresholdPercentage"></a>circuitBreaker.errorThresholdPercentage</h3><p>设置异常请求量的百分比，当异常请求达到这个百分比时，就触发打开短路器，默认是50，也就是50%</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">HystrixCommandProperties.Setter()</span><br><span class="line">   .withCircuitBreakerErrorThresholdPercentage(<span class="keyword">int</span> value)</span><br></pre></td></tr></table></figure>
<p>我们最好还是自己定制，自己设置，如果是要50%的时候才短路的话，会有什么情况呢?10%短路，也不太靠谱，90%异常，才短路也不行。这个值可以稍微高一些，如果redis集群彻底崩溃，那么基本上就是所有的请求，100%都会异常，所以一般设置60%，70%。也有可能偶然出现网络的抖动，导致比如说就这10秒钟，访问延时高了一些，其实可能并不需要立即就短路，可能下个10秒马上就恢复了。</p>
<p>金融支付类的接口，可能这个比例就会设置的很低，因为对异常系统必须要很敏感，可能就是10%异常了，就直接短路了，不让继续访问了。金融支付类的接口是很重要的，而且必须是很稳定，我们不能容忍任何的延迟或者是报错。一旦支付类的接口，有10%的异常的话，我们基本就可以认为这个接口已经出问题了，再继续访问的话，也许访问的就是有问题的接口，可能造成资金的错乱，给公司造成损失。所以直接熔断吧，不让访问了，走降级策略，这就是对整个系统的一个安全性保障。</p>
<h3 id="circuitBreaker-sleepWindowInMilliseconds"><a href="#circuitBreaker-sleepWindowInMilliseconds" class="headerlink" title="circuitBreaker.sleepWindowInMilliseconds"></a>circuitBreaker.sleepWindowInMilliseconds</h3><p>设置在短路之后，需要在多长时间内直接reject请求，然后在这段时间之后，再重新导half-open状态，尝试允许请求通过以及自动恢复，默认值是5000毫秒</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">HystrixCommandProperties.Setter()</span><br><span class="line">   .withCircuitBreakerSleepWindowInMilliseconds(<span class="keyword">int</span> value)</span><br></pre></td></tr></table></figure>
<p>如果redis集群崩溃了，会在5s内就直接恢复。</p>
<h1 id="Hystrix保护源服务，防止Mysql崩溃"><a href="#Hystrix保护源服务，防止Mysql崩溃" class="headerlink" title="Hystrix保护源服务，防止Mysql崩溃"></a>Hystrix保护源服务，防止Mysql崩溃</h1><p>做缓存服务，redis集群彻底崩溃的时候，除了对redis本身做资源隔离、超时控制、熔断策略。还要保护源服务，因为Redis集群崩溃后，大量的请求会高并发会去访问源服务-商品服务（提供商品数据）。如果QPS10000去访问商品服务，基于mysql去查询，那mysql肯定会挂掉，商品服务也就死掉了。</p>
<p>所以要对商品服务这种源服务的访问施加限流的措施，限流怎么限，hystrix本身就是提供了两种机制，线程池（内部做了异步化处理，可以处理超时），semaphore（信号量，让tomcat线程执行运行逻辑，没有内部的异步化处理，一旦超时，会导致tomcat线程就hang住了）。</p>
<p>一般推荐线程池用来做有网络访问的这种资源隔离，因为涉及到网络，就很容易超时；sempahore是用来做对服务纯内存的一些复杂业务逻辑的操作进行限流，因为不涉及网络访问，就是纯粹为了避免说对内存内的复杂业务逻辑进行太高并发的访问，造成系统本身的故障。semaphore在以下情况是很合适的：比如一些推荐、搜索，有部分算法，复杂的算法，是放在服务内部纯内存去运行的，一个服务暴露出来的就是某个算法的执行。</p>
<p>我们这里是访问外部的商品服务，所以还是用线程池做限流，需要算一下，要限多少，怎么限？</p>
<p>假设每次商品服务的访问性能在200ms，1个线程一秒可以执行5次访问，假设我们一个缓存服务实例对这个商品服务的访问每秒在150次。所以这个时候，我们就需要30个线程，每个线程每秒可以访问5次，总共每秒30个线程可以访问150次。</p>
<p>我们算的这个每秒150次访问时正常情况下，如果是非正常情况下，每秒1000次，甚至1w次，此时就可以自然限流，因为我们的线程池就30个。在非正常情况下，直接线程池+等待队列全满，此时就会出现大量的reject操作，然后就会去调用降级逻辑。接着我们要做限流，设置的就是线程池的大小，还有等待队列的大小，30个线程可以每秒处理150个请求，但是偶尔会多一些出来，同时30个线程处理150个请求会快一些，不用花费1秒钟，等待队列给一些buffer，不要偶尔1秒钟来了200条请求，50条直接给reject掉了。等待队列设置150个，30个线程直接500ms处理完了，等待队列中的50个请求就可以继续处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetProductInfoCommand</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">ProductInfo</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long productId;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GetProductInfoCommand</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(<span class="string">"ProductInfoService"</span>))</span><br><span class="line">                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(<span class="string">"GetProductInfoPool"</span>))</span><br><span class="line">                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()</span><br><span class="line">                        .withCoreSize(<span class="number">10</span>)</span><br><span class="line">                        .withMaxQueueSize(<span class="number">12</span>)</span><br><span class="line">                        .withQueueSizeRejectionThreshold(<span class="number">8</span>)</span><br><span class="line">                        .withMaximumSize(<span class="number">30</span>)</span><br><span class="line">                        .withAllowMaximumSizeToDivergeFromCoreSize(<span class="keyword">true</span>)</span><br><span class="line">                        .withKeepAliveTimeMinutes(<span class="number">1</span>)</span><br><span class="line">                        .withMaxQueueSize(<span class="number">50</span>)</span><br><span class="line">                        .withQueueSizeRejectionThreshold(<span class="number">100</span>))</span><br><span class="line">                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()</span><br><span class="line">                        <span class="comment">// 多少个请求以上才会判断断路器是否需要开启。</span></span><br><span class="line">                        .withCircuitBreakerRequestVolumeThreshold(<span class="number">30</span>)</span><br><span class="line">                        <span class="comment">// 错误的请求达到40%的时候就开始断路。</span></span><br><span class="line">                        .withCircuitBreakerErrorThresholdPercentage(<span class="number">40</span>)</span><br><span class="line">                        <span class="comment">// 3秒以后尝试恢复</span></span><br><span class="line">                        .withCircuitBreakerSleepWindowInMilliseconds(<span class="number">4000</span>))</span><br><span class="line">        );</span><br><span class="line">        <span class="keyword">this</span>.productId = productId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> ProductInfo <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        String productInfoJSON = <span class="string">"&#123;\"id\": "</span> + productId + <span class="string">", \"name\": \"iphone7手机\", \"price\": 5599, \"pictureList\":\"a.jpg,b.jpg\", \"specification\": \"iphone7的规格\", \"service\": \"iphone7的售后服务\", \"color\": \"红色,白色,黑色\", \"size\": \"5.5\", \"shopId\": 1, \"modifiedTime\": \"2017-01-01 12:01:00\"&#125;"</span>;</span><br><span class="line">        <span class="keyword">return</span> JSONObject.parseObject(productInfoJSON, ProductInfo.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="源服务fallback降级机制"><a href="#源服务fallback降级机制" class="headerlink" title="源服务fallback降级机制"></a>源服务fallback降级机制</h2><p>现在nginx本地缓存没有，redis集群崩溃，ehcache也找不到这条数据对应的缓存，只能去源头服务里面查询，但是查询的请求又被限流了，现在请求到了这里，被限流了以后只能走降级逻辑。</p>
<p>这里的一种降级机制叫做<a href="http://www.saily.top/2018/04/15/hystrix03/">stubbed fallback降级机制</a>（残缺的降级），就是用请求参数中少量的数据，加上纯内存中缓存的少量的数据来提供残缺的数据服务。</p>
<h1 id="缓存雪崩预防和解决方案回顾"><a href="#缓存雪崩预防和解决方案回顾" class="headerlink" title="缓存雪崩预防和解决方案回顾"></a>缓存雪崩预防和解决方案回顾</h1><ol>
<li><p>事前，redis高可用性，redis cluster，sentinal，复制，主从，从-&gt;主，双机房部署</p>
</li>
<li><p>事中，ehcache可以扛一扛，redis挂掉之后的资源隔离、超时控制、熔断，商品服务的访问限流、多级降级，缓存服务在雪崩场景下存活下来，基于ehcache和存活的商品服务提供数据</p>
</li>
<li><p>事后，快速恢复Redis，备份+恢复，快速的缓存预热的方案</p>
</li>
</ol>
<h1 id="缓存穿透"><a href="#缓存穿透" class="headerlink" title="缓存穿透"></a>缓存穿透</h1><p>如果一直访问的根本不存在的时候，那么就会导致缓存穿透，所有的这种请求都会直接到mysql这边来。</p>
<p><img src="/img/cache/缓存穿透的现象.png" alt="缓存穿透的现象"></p>
<p>缓存穿透的解决方案其实非常简单，就是如果从源服务（商品服务）查询到的数据是空，就说明这个数据根本就不存在。那么如果这个数据不存在的话，我们也往redis和ehcache等缓存中写入一个数据，可以写入一个空的数据，比如说空的productInfo的json串，给nginx也是，返回一个空的productInfo的json串。</p>
<p>我们有异步监听数据变更的机制在里面，如果数据变更的话，某个数据本来是没有的，可能会导致缓存穿透，所以我们给了个空数据，但是现在这个数据有了，我们接收到这个变更的消息过后，就可以将数据再次从源服务中查询出来，然后设置到各级缓存中去了。</p>
<h1 id="缓存失效"><a href="#缓存失效" class="headerlink" title="缓存失效"></a>缓存失效</h1><p>之前在nginx中设置本地的缓存的时候，给了一个过期的时间（10分钟）。10分钟以后自动过期，过期了以后，就会重新从redis中去获取数据。10分钟到期自动过期，就叫做缓存的失效。如果缓存失效以后，那么实际上此时，就会有大量的请求回到redis中去查询。</p>
<p>如果说同一时间来了1000个请求，都将缓存cache在了nginx自己的本地，缓存失效的时间都设置了10分钟，那么是不是可能导致10分钟过后，这些数据，就自动全部在同一时间失效了。如果同一时间全部失效，会不会导致说同一时间大量的请求过来，在nginx里找不到缓存数据，全部高并发走到redis上去了。加重大量的网络请求，网络负载也会加重。</p>
<p>解决方案很简单，就是把10分钟的时间改成一个随机数,随机一个失效的时间。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">math.randomseed(tostring(os.time()):reverse():sub(1, 7))</span><br><span class="line"><span class="built_in">local</span> expireTime = math.random(600, 1200)</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/多级缓存架构/" rel="tag"># 多级缓存架构</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/10/hystrix04/" rel="next" title="Hystrix监控和运维">
                <i class="fa fa-chevron-left"></i> Hystrix监控和运维
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/20/elasticSearch03/" rel="prev" title="ElasticSearch03-集群和架构讲解">
                ElasticSearch03-集群和架构讲解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#缓存雪崩"><span class="nav-number">1.</span> <span class="nav-text">缓存雪崩</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#缓存雪崩的过程和后果"><span class="nav-number">1.1.</span> <span class="nav-text">缓存雪崩的过程和后果</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#缓存雪崩的解决方案"><span class="nav-number">2.</span> <span class="nav-text">缓存雪崩的解决方案</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#事前解决方案"><span class="nav-number">2.1.</span> <span class="nav-text">事前解决方案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事中解决方案"><span class="nav-number">2.2.</span> <span class="nav-text">事中解决方案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事后解决方案"><span class="nav-number">2.3.</span> <span class="nav-text">事后解决方案</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用Hystrix对Redis进行资源隔离"><span class="nav-number">3.</span> <span class="nav-text">使用Hystrix对Redis进行资源隔离</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#SaveProductInfo2RedisCacheCommand"><span class="nav-number">3.1.</span> <span class="nav-text">SaveProductInfo2RedisCacheCommand</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SaveShopInfo2RedisCacheCommand"><span class="nav-number">3.2.</span> <span class="nav-text">SaveShopInfo2RedisCacheCommand</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GetProductInfoFromRedisCacheCommand"><span class="nav-number">3.3.</span> <span class="nav-text">GetProductInfoFromRedisCacheCommand</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GetShopInfoFromRedisCacheCommand"><span class="nav-number">3.4.</span> <span class="nav-text">GetShopInfoFromRedisCacheCommand</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用Hystrix对Redis访问进行降级"><span class="nav-number">4.</span> <span class="nav-text">使用Hystrix对Redis访问进行降级</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis集群崩溃定制化熔断策略"><span class="nav-number">5.</span> <span class="nav-text">Redis集群崩溃定制化熔断策略</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#timeout设置"><span class="nav-number">5.1.</span> <span class="nav-text">timeout设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#熔断策略"><span class="nav-number">5.2.</span> <span class="nav-text">熔断策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#circuitBreaker-requestVolumeThreshold"><span class="nav-number">5.2.1.</span> <span class="nav-text">circuitBreaker.requestVolumeThreshold</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#circuitBreaker-errorThresholdPercentage"><span class="nav-number">5.2.2.</span> <span class="nav-text">circuitBreaker.errorThresholdPercentage</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#circuitBreaker-sleepWindowInMilliseconds"><span class="nav-number">5.2.3.</span> <span class="nav-text">circuitBreaker.sleepWindowInMilliseconds</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix保护源服务，防止Mysql崩溃"><span class="nav-number">6.</span> <span class="nav-text">Hystrix保护源服务，防止Mysql崩溃</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#源服务fallback降级机制"><span class="nav-number">6.1.</span> <span class="nav-text">源服务fallback降级机制</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#缓存雪崩预防和解决方案回顾"><span class="nav-number">7.</span> <span class="nav-text">缓存雪崩预防和解决方案回顾</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#缓存穿透"><span class="nav-number">8.</span> <span class="nav-text">缓存穿透</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#缓存失效"><span class="nav-number">9.</span> <span class="nav-text">缓存失效</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
